package org.jsg1904.study001.service.serviceImpl;

import org.jsg1904.study001.service.MyAccessService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author: 默苍璃
 * @date: 2022-02-11 14:40
 */
@Service
public class MyAccessServiceImpl implements MyAccessService {

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        // 获取主体
        Object principal = authentication.getPrincipal();

        // 判断主体是否属于UserDetails
        if (principal instanceof UserDetails) {

            // 获取权限
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

            String requestURI = request.getRequestURI();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(requestURI);

            // 判断请求的URI是否在权限里
            boolean contains = authorities.contains(simpleGrantedAuthority);

            return contains;

        }

        return false;
    }

}
